package org.csu.onlineedubackend.controller;

import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.dto.FaceRegisterRequest;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.mapper.UserMapper;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.FaceService;
import org.csu.onlineedubackend.service.UserService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.csu.onlineedubackend.dto.FaceLoginRequest;

import java.util.Map;

@RestController
@RequestMapping("/api/face")
@Slf4j
public class FaceController {

    private final FaceService faceService;
    private final UserService userService;
    private final UserMapper userMapper;

    @Value("${baidu.aip.group-id}")
    private String groupId;

    public FaceController(FaceService faceService, UserService userService, UserMapper userMapper) {
        this.faceService = faceService;
        this.userService = userService;
        this.userMapper = userMapper;
    }

    @PostMapping("/register")
    public CommonResponse<?> registerFace(@RequestBody FaceRegisterRequest request) {
        if (request.getImage() == null || request.getUserId() == null) {
            return CommonResponse.createForError(ResponseCode.ARGUMENT_INVALID.getCode(), "图像和用户ID不能为空");
        }

        User user = userMapper.selectById(request.getUserId());
        if (user == null) {
            return CommonResponse.createForError(ResponseCode.USER_NOT_EXIST.getCode(), ResponseCode.USER_NOT_EXIST.getDescription());
        }

        // 图像格式处理，去掉base64头
        String image = request.getImage();
        String imageType = "BASE64";
        if (image.contains(",")) {
            image = image.substring(image.indexOf(",") + 1);
        }

        String userIdStr = String.valueOf(request.getUserId());

        try {
            // 先检查该人脸是否已经在人脸库中存在
            JSONObject searchRes = faceService.search(image, imageType, groupId);
            log.info("Face search response: {}", searchRes.toString(2));
            
            // 如果搜索成功并且找到匹配的人脸
            if (searchRes.has("error_code") && searchRes.getInt("error_code") == 0) {
                JSONObject result = searchRes.getJSONObject("result");
                if (result != null && result.has("user_list") && result.getJSONArray("user_list").length() > 0) {
                    // 获取匹配用户信息并验证分数
                    JSONObject userPayload = result.getJSONArray("user_list").getJSONObject(0);
                    double score = userPayload.getDouble("score");
                    
                    // 如果置信度大于80，认为是同一个人脸
                    if (score > 80) {
                        String existingUserId = userPayload.getString("user_id");
                        
                        // 如果匹配的不是当前用户的人脸，则说明人脸已被其他账号注册
                        if (!existingUserId.equals(userIdStr)) {
                            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "该人脸已被其他账号注册");
                        }
                        // 如果是同一用户，允许更新
                    }
                }
            }
            
            // 执行注册
            JSONObject res = faceService.register(image, imageType, userIdStr, groupId);
            log.info("Baidu AI registration response: {}", res.toString(2));

            if (res.has("error_code") && res.getInt("error_code") == 0) {
                // 注册成功，更新数据库
                userService.updateFaceRegisteredStatus(request.getUserId(), true);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "人脸注册成功");
            } else {
                // 注册失败
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), res.getString("error_msg"));
            }
        } catch (Exception e) {
            log.error("Face registration failed", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "人脸注册服务异常，请稍后再试");
        }
    }

    @PostMapping("/login")
    public CommonResponse<?> loginByFace(@RequestBody FaceLoginRequest request) {
        // 1. 基本参数验证
        if (request.getImage() == null) {
            return CommonResponse.createForError(ResponseCode.ARGUMENT_INVALID.getCode(), "图像不能为空");
        }

        // 2. 图像格式处理，去掉base64头
        String image = request.getImage();
        String imageType = "BASE64";
        if (image.contains(",")) {
            image = image.substring(image.indexOf(",") + 1);
        }

        try {
            // 3. 调用百度AI人脸搜索服务
            JSONObject res = faceService.search(image, imageType, groupId);
            log.info("Baidu AI Face Search response: {}", res.toString(2));

            // 4. 处理百度AI返回的错误
            if (res.has("error_code") && res.getInt("error_code") != 0) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), res.getString("error_msg"));
            }

            // 5. 处理搜索结果为空的情况
            JSONObject result = res.getJSONObject("result");
            if (result == null || !result.has("user_list") || result.getJSONArray("user_list").length() == 0) {
                return CommonResponse.createForError(ResponseCode.USER_NOT_EXIST.getCode(), "识别人脸失败，未找到匹配用户");
            }

            // 6. 获取匹配用户信息并验证分数
            JSONObject userPayload = result.getJSONArray("user_list").getJSONObject(0);
            double score = userPayload.getDouble("score");
            if (score < 80) {
                return CommonResponse.createForError(ResponseCode.USER_NOT_EXIST.getCode(), "人脸匹配度不足，请调整姿势或光线后重试");
            }

            // 7. 获取用户ID并执行登录
            Integer userId = Integer.valueOf(userPayload.getString("user_id"));
            
            // 8. 如果请求中提供了userId，验证是否匹配
            if (request.getUserId() != null && !request.getUserId().equals(userId)) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "人脸与用户不匹配");
            }
            
            // 9. 执行登录操作
            Map<String, Object> loginResult = userService.loginById(userId);
            
            // 10. 返回成功响应
            return CommonResponse.createForSuccess(
                ResponseCode.UserLoginSuccess.getCode(),
                "人脸登录成功",
                loginResult
            );
        } catch (Exception e) {
            log.error("Face login failed", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "人脸登录服务异常: " + e.getMessage());
        }
    }
} 